package com.huangmingfu;

import java.util.Random;

/**
 * @Author: 黄名富
 * @Description: 不使用中介者模式
 * @需求描述: 在前端开发中，有三个组件 Button、View, 及Text. View 用来展示信息，Text 用于输入编辑信息，Button用来提交更新。
 * 用户在Text输入好内容后，点击Button后，内容会更新到View. 而点击View时，会把内容输入到Text。
 */
public class NoMediatorPattern {

    public static void main(String[] args) {
        Text text = new Text();
        Button button = new Button();
        View view = new View();

        button.setText(text);
        button.setView(view);
        view.setText(text);

        button.click();
        view.click();
        button.click();
    }

    private static class Button {

        private Text text;
        private View view;

        public void setText(Text text) {
            this.text = text;
        }

        public void setView(View view) {
            this.view = view;
        }

        void click() {
            if (text != null && view != null) {
                view.onRefresh(text.generateText());
            }
        }
    }

    private static class Text  {

        private String content;

        private String generateText() {
            if (content == null) content = "";
            Random random = new Random();
            content += random.nextInt();
            return content;
        }

        void onRefresh(String text) {
            content = text;
        }
    }

    private static class View{

        private Text text;

        private String content;

        public void setText(Text text) {
            this.text = text;
        }

        void click() {
            if (text != null) {
                text.onRefresh(content);
            }
        }

        void onRefresh(String text) {
            this.content = text; // 更新信息
            System.out.println("View中显示信息:" + text);
        }
    }

}
